import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { deleteCartGoodsApi, getCartListApi, updateCartApi } from '@/api/cart'
import { showToast } from 'vant'

export const useCartStore = defineStore(
  'cart',
  () => {
    const cartList = ref([])

    const getCartList = async () => {
      const { data } = await getCartListApi()
      cartList.value = data.list.map(item => ({
        ...item,
        isChecked: true
      }))
    }

    // 求购物车中所有商品总数
    const cartGoodsTotal = computed(() => {
      return cartList.value.reduce((total, item) => total + item.goods_num, 0)
    })

    // 选中的商品
    const checkedGoods = computed(() => {
      return cartList.value.filter(item => item.isChecked)
    })

    // 选中商品总数
    const checkedGoodsTotal = computed(() => {
      return checkedGoods.value.reduce((total, item) => total + item.goods_num, 0)
    })

    // 选中商品总价
    const checkedGoodsTotalPrice = computed(() => {
      return checkedGoods.value.reduce((total, item) => total + item.goods_num * item.goods.goods_price_min, 0).toFixed(2)
    })

    // 是否全选
    const isAllChecked = computed({
      get: () => {
        return cartList.value.length > 0 && cartList.value.every(item => item.isChecked)
      },
      set: (value) => {
        cartList.value.forEach(item => {
          item.isChecked = value
        })
      }
    })

    const updateCart = async (goodsId, goodsNum, goodsSkuId) => {
      updateCartApi(goodsId, goodsNum, goodsSkuId)
    }

    const deleteCartGoods = async () => {
      const cartIds = checkedGoods.value.map(item => item.id)
      await deleteCartGoodsApi(cartIds)
      showToast('删除成功')
      getCartList()
    }

    const logout = () => {
      cartList.value = []
    }

    return {
      cartList,
      getCartList,
      cartGoodsTotal,
      checkedGoods,
      checkedGoodsTotal,
      checkedGoodsTotalPrice,
      isAllChecked,
      updateCart,
      deleteCartGoods,
      logout
    }
  }, {
    persist: {
      key: 'cart', // 指定存储的 key
      storage: localStorage // 指定存储方式，默认是 localStorage
    }
  })
